package com.basin.micro.auth.module.role.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.basin.common.core.exception.BasinException;
import com.basin.micro.auth.module.role.pojo.dto.RoleDTO;
import com.basin.micro.auth.module.role.pojo.entity.RoleEntity;
import com.basin.micro.auth.module.role.repository.RoleRepository;
import com.basin.micro.auth.module.role.service.RoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@Service
@Slf4j(topic = "BASIN:ADMIN:ROLE_SERVICE")
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {
    private final RoleRepository roleRepository;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean add(RoleDTO roleDTO) {
        // 数据唯一性校验
        long count = this.roleRepository.count(Wrappers.<RoleEntity>lambdaQuery()
                .eq(RoleEntity::getRoleCode, roleDTO.getRoleCode()));
        if (count > 0) {
            log.error("Role code already exists, roleDTO: {}", roleDTO);
            throw new BasinException("角色编码已存在库中");
        }
        RoleEntity roleEntity = RoleEntity.builder()
                .roleCode(roleDTO.getRoleCode())
                .roleName(roleDTO.getRoleName())
                .roleDesc(roleDTO.getRoleDesc())
                .roleStatus(roleDTO.getRoleStatus())
                .build();
        // 主表保存
        boolean save = this.roleRepository.save(roleEntity);
        if (!save) {
            log.error("Add role failed, roleDTO: {}", roleDTO);
            throw new BasinException("添加角色失败");
        }
        return true;
    }

    @Override
    public boolean update(RoleDTO roleDTO) {
        // 数据是否存在
        String roleCode = roleDTO.getRoleCode();
        RoleEntity dbData = this.roleRepository.getOne(Wrappers.<RoleEntity>lambdaQuery()
                .eq(RoleEntity::getRoleCode, roleCode));
        if (dbData == null) {
            log.error("Role not found, roleDTO: {}", roleDTO);
            throw new BasinException("修改角色不存在");
        }
        // 主表更新
        dbData.setRoleStatus(roleDTO.getRoleStatus());
        dbData.setRoleName(roleDTO.getRoleName());
        dbData.setRoleDesc(roleDTO.getRoleDesc());
        boolean update = this.roleRepository.updateById(dbData);
        if (!update) {
            log.error("Update role failed, roleDTO: {}", roleDTO);
            throw new BasinException("修改角色失败");
        }
        return true;
    }
}
